'use client'
import {Button, Checkbox, Flex, Form, Input} from "antd";
import FootBar from "@/app/components/footbar";
import React from "react";
import { postFetch} from "@/app/lib/HttpProtocol";
import {homeUrl, persistToken, setToken} from "@/app/lib/security";
import {useRouter} from "next/navigation";
const apis = {
  loginApi:'/auth/login'
}

const bodyContentStyle: React.CSSProperties = {
  width:'100%',
  minHeight: '100vh',
};

type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};

export default function Home() {
  let router = useRouter();
  const onFinish = (values: any) => {
    postFetch(apis.loginApi, values).then(res => {
      // @ts-ignore
      setToken(res);
      if(values.remember){
        // @ts-ignore
        persistToken(res);
      }
      router.push(homeUrl);
    })
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  return (
    <Flex vertical={true} style={bodyContentStyle}>
      <div style={{width:'100%',height:'100%',justifyContent:"center",display:"flex"}}>
        <div style={{width:500,height:300,marginTop:100,backgroundColor:'#fafafa',justifyContent:"center",display:"flex",alignItems:"center"}}>
          <Form
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 500 }}
            size={"large"}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item<FieldType>
              label="用户名"
              name="username"
              rules={[{ required: true, message: '请输入用户名!' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item<FieldType>
              label="密码"
              name="password"
              rules={[{ required: true, message: '请输入密码!' }]}
            >
              <Input.Password />
            </Form.Item>

            <Form.Item<FieldType>
              name="remember"
              valuePropName="checked"
              wrapperCol={{ offset: 8, span: 16 }}
            >
              <Checkbox>Remember me</Checkbox>
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button type="primary" htmlType="submit">
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
      <FootBar/>
    </Flex>
  );
}
